package chances.epg.navigator.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.data.service.ContentService;
import chances.epg.entity.content.SubjectPage;
import chances.epg.navigator.EpgConstants;
import chances.epg.navigator.context.AccessContext;
import chances.epg.navigator.controller.ItemAccessController;


/**
 * 对于Item访问时，需要将专辑的编码替换为专辑首页的编码.
 * @author Elysium
 *
 */
@Component
public class SubjectFirstPageInterceptor extends HandlerInterceptorAdapter {
	private static Logger logger = EpgLogFactory.getSystemLogger();
	
	@Autowired
	private ContentService contentService;
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if(!(handler instanceof ItemAccessController)){
			super.postHandle(request, response, handler, modelAndView);
			return;
		}
		
		if(modelAndView == null) {
            super.postHandle(request, response, handler, modelAndView);
            return;
        }
		
		AccessContext context = (AccessContext)modelAndView.getModelMap().get(EpgConstants.EPG_CONTEXT);
		if(context == null){
			super.postHandle(request, response, handler, modelAndView);
			return;
		}
		
		String contentType = context.getContentType();
		if("subject".equals(contentType)){
			String contentCode = context.getContentCode();
			SubjectPage subjectPage = this.contentService.getDefaultPageOfSubject(contentCode);
			if(subjectPage != null){
			    context.setContentCode(subjectPage.getPageCode());
			}else{
				logger.error("Can't found subject default page,subject code={}",contentCode);
			}
		}
		
		super.postHandle(request, response, handler, modelAndView);
	}

	public void setContentService(ContentService contentService) {
		this.contentService = contentService;
	}
}
